package mysql;

import utils.titles.Title;
import mysql.types.Type;

/**
 * Created by thormentor on 27-04-2014.
 */
public class Column extends MySQL.Object {

    private final Table table;
    private final Type type;
    private final boolean isNullable;
    private final Key key;
    private final String defaultValue;
    private Reference reference;
    private boolean primary;

    public Column(Table table, String name, Type type, Boolean isNullable, String key, String defaultValue, String extra) {
        super(Title.fromSnakeCase(name));

        this.table = table;
        this.type = type;
        this.isNullable = isNullable;
        this.key = key == null || key.length() == 0 ? null : Key.valueOf(key);
        this.defaultValue = defaultValue;
        this.extra = extra;
    }

    public String getExtra() {
        return extra;
    }

    public String getDefaultValue() {
        return defaultValue;
    }

    public Key getKey() {
        return key;
    }

    public Type getType() {
        return type;
    }

    public Table getTable() {
        return table;
    }

    private final String extra;

    public boolean isNullable() {
        return isNullable;
    }

    public boolean isPrimary() {
        return primary;
    }

    public void reference(String name, Table table, Column column) {
        reference = new Reference(name, table, column);

        if (primary)
            this.table.addDependency(name, table);
    }

    public Reference getReference() {
        return reference;
    }

    public void setPrimary() {
        primary = true;
    }

    public enum Key {
        PRI, MUL, UNI
    }

    public class Reference {
        private final String name;
        private final Table table;
        private final Column column;

        public Reference(String name, Table table, Column column) {
            this.name = name;
            this.table = table;
            this.column = column;
        }

        public String getName() {
            return name;
        }

        public Column getColumn() {
            return column;
        }

        public Table getTable() {
            return table;
        }
    }
}
